package org.example.demo3.config;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.example.demo3.untils.JwtUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtUtil jwtUtil;

    @Override
// 重写父类的方法，用于执行过滤器内部逻辑
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

    // 从请求头中获取"Authorization"字段的值
        String authHeader = request.getHeader("Authorization");

    // 检查请求头是否存在且以"Bearer "开头
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
        // 从请求头中提取出令牌，去掉"Bearer "前缀
            String token = authHeader.substring(7);
        // 使用jwtUtil工具类验证令牌，获取用户ID
            Long userId = jwtUtil.validateAccessToken(token);

        // 如果令牌验证成功，用户ID不为空
            if (userId != null) {
                // 设置认证信息到Security上下文
                UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(userId, null, null);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }

        filterChain.doFilter(request, response);
    }
}